﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleRest.Serialization
{
    public class UrlEncodedFormPostSerializer
    {
        public object DeSerialize(Type type, Dictionary<string, string> formData)
        {
            return this.DeSerializeImpl(type, formData);
        }
        public T DeSerialize<T>(Dictionary<string, string> formData)
        {
            return (T)Convert.ChangeType(this.DeSerialize(typeof(T), formData), typeof(T));
        }

        private object DeSerializeImpl(Type type, Dictionary<string, string> values)
        {
            object obj = System.Activator.CreateInstance(type);

            foreach (var property in type.GetProperties())
            {
                if (TypeCache.PrimitiveTypes.Contains(property.PropertyType))
                {
                    if (values.ContainsKey(property.Name))
                    {
                        var exactMatch = values[property.Name];
                        if (exactMatch != null)
                        {
                            property.SetValue(obj, Convert.ChangeType(exactMatch, property.PropertyType), null);
                            values.Remove(property.Name);
                        }
                    }
                }
                else if (property.PropertyType.GetInterface(typeof(System.Collections.IEnumerable).FullName) != null)
                {
                    if (property.PropertyType.GetInterface(typeof(System.Collections.IList).FullName) == null)
                        throw new NotSupportedException("Can only serialize collections that extend System.Collections.IList."); // must be of type IList
                    throw new NotImplementedException();
                }
                else // complex type, non array
                {
                    throw new NotImplementedException();
                }
            }

            return obj;
        }

        public bool CanDeserialize(Type type)
        {
            foreach (var property in type.GetProperties())
                if (!TypeCache.PrimitiveTypes.Contains(property.PropertyType))
                    return false;
            return true;
        }
    }
}
